package utils

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"goadmin/logs"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

// SendAdminNoticeMsg 给管理员下发后台下单提醒短信
func SendAdminNoticeMsg(name, phone, time string) (bool, error) {
	const (
		templateCode = "SMS_492525556"
		signName     = "上海净致信息科技服务"
		accessKeyId  = "LTAI5t9Mp5PeXZAc1x7nqSmC"
		accessSecret = "d5LkAPUHG5nIjGlNtAO8GWvTcpCRXz"
		targetPhone  = "17326062026" // 接收管理员手机号
	)
	params := gin.H{
		"phone": phone,
		"name":  name,
		"time":  time,
	}
	logs.Sugar().Info("发送短信的参数", params)

	// 2. 创建客户端
	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessSecret)
	if err != nil {
		logs.Sugar().Error("创建短信客户端失败", err)
		return false, err
	}

	// 3. 组装请求
	req := requests.NewCommonRequest()
	req.Method = "POST"
	req.Scheme = "https"
	req.Domain = "dysmsapi.aliyuncs.com"
	req.Version = "2017-05-25"
	req.ApiName = "SendSms"

	// 4. 业务参数
	req.QueryParams["PhoneNumbers"] = targetPhone
	req.QueryParams["SignName"] = signName
	req.QueryParams["TemplateCode"] = templateCode

	// 模板变量 JSON
	templateParam, _ := json.Marshal(map[string]string{
		"name":  name,
		"phone": phone,
		"time":  time,
	})
	req.QueryParams["TemplateParam"] = string(templateParam)
	req.QueryParams["OutId"] = "demo"

	// 5. 发起调用
	resp, err := client.ProcessCommonRequest(req)
	if err != nil {
		logs.Sugar().Error("短信API调用失败", err)
		return false, err
	}

	// 6. 打印返回
	logs.Sugar().Info("发送短信后的返回信息", resp.GetHttpContentString())
	// 7. 判断结果
	var body struct {
		Code string `json:"Code"`
	}
	_ = json.Unmarshal(resp.GetHttpContentBytes(), &body)
	if body.Code == "OK" {
		return true, nil
	}
	return false, fmt.Errorf("sms error code: %s", body.Code)
}
